<template>
	<view>
		<u-navbar leftIconSize="0" title="我的" bgColor="transparent" placeholder></u-navbar>
		<view class="box">
			<view class="head zdy-flex zdy-flex-direction zdy-flex-align-center">
				<div class="img">
					<image :src="userInfo.avatarUrl || '/static/img/housing/lxr.png'" mode=""></image>
				</div>
				<view class="nickNameSty">{{ userInfo.nickName || '未知' }}</view>
				<view class="zdy-flex zdy-flex-between" style="width: 65%">
					<view class="nickNameSty" @click="recorShow = true">
						<view class="integral" :style="{ color: userInfo.integral >= 0 ? 'red' : 'green' }">{{ userInfo.integral || 0 }}</view>
						<view class="label" style="text-decoration: underline">累计积分 ></view>
					</view>
					<view class="nickNameSty">
						<view class="session">{{ userInfo.totalSession || 0 }}</view>
						<view class="label">总场次</view>
					</view>
				</view>
			</view>
			<u-cell-group :border="false" :customStyle="customStyleObj">
				<u-cell size="large" icon="account-fill" title="头像" isLink>
					<div slot="value" style="width: 70%">
						<button class="btnImg" open-type="chooseAvatar" @chooseavatar="editUserInfo">
							<image style="width: 50rpx; height: 50rpx; border-radius: 50%" :src="userInfo.avatarUrl || '/static/img/housing/lxr.png'" mode=""></image>
						</button>
					</div>
				</u-cell>
				<u-cell size="large" icon="coupon-fill" title="昵称" :value="userInfo.nickName" :border="false" isLink>
					<input slot="value" type="nickname" :value="userInfo.nickName" @blur="valueChange" />
				</u-cell>
			</u-cell-group>
			<view class="begin" @click="tnRoom">{{ recordInfo.status == 1 ? '加入' : '开始' }}对局</view>
			<!-- <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button> -->
		</view>
		<u-popup :round="10" :customStyle="{ height: '800rpx' }" :show="recorShow" mode="bottom" @close="recorShow = false">
			<view class="recordBox">
				<u-cell-group :border="false" v-if="recordList.length">
					<u-cell v-for="(item, index) in recordList" :key="index" center>
						<view slot="title">{{ item.createDate }}</view>
						<view slot="value">
							<text :style="{ color: item.newIntegral >= 0 ? 'red' : 'green', fontWeight: 'bold' }">{{ item.newIntegral }}</text>
						</view>
					</u-cell>
				</u-cell-group>
				<u-empty marginTop="200rpx" v-else mode="history"></u-empty>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { getCodImg, getOpenid, login, getUserInfo, editUserInfo } from '@/api/user.js';
import { addRecord, getRecord, putRecord } from '@/api/record.js';
import upImg from '@/utils/upImg.js';
export default {
	data() {
		return {
			recorShow: false,
			userInfo: uni.getStorageSync('userInfo'),
			recordId: '',
			customStyleObj: {
				'background-color': '#ffffff',
				padding: '0 30rpx',
				'border-radius': '10rpx'
			},
			recordInfo: {} //扫码参与的活动
		};
	},
	onPullDownRefresh() {
		uni.showLoading();
		this.getUser();
	},
	onLoad(option) {
		if (option.scene) {
			this.recordId = option.scene;
		}
	},
	computed: {
		recordList() {
			if (this.userInfo.recordList) {
				return this.userInfo.recordList && this.userInfo.recordList.reverse();
			} else {
				return [];
			}
		}
	},
	async onShow() {
		this.userInfo = uni.getStorageSync('userInfo');
		uni.showLoading();
		this.resetLogin();
		if (this.recordId) {
			// const record = await this.$cloudRequest('record', { type: 'getRecord', recordId: this.recordId });
			//1未结束游戏，0已结束游戏
			const record = await getRecord({ id: this.recordId });
			if (record.status == 1) {
				this.recordInfo = record;
				this.editInfo({ recordId: this.recordId });
			}
		}
	},
	methods: {
		resetLogin() {
			const that = this;
			this.$Message(this.userInfo.openid);
			if (!this.userInfo.openid) {
				uni.login({
					success: function (res) {
						getOpenid(res.code).then((codes) => {
							uni.getUserInfo({
								desc: '获取用户信息，进行登录',
								success: (res) => {
									const data = { ...res.userInfo, openid: codes.openid };
									//调用登录函数
									that.getLogin(data);
								}
							});
						});
					}
				});
			} else {
				this.getUser();
			}
		},
		// 微信登录
		getLogin(userInfo) {
			login(userInfo)
				.then((res) => {
					uni.setStorageSync('userInfo', res);
					this.userInfo = res;
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		//获取用户信息
		getUser() {
			getUserInfo()
				.then((res) => {
					uni.setStorageSync('userInfo', res);
					this.userInfo = res;
				})
				.catch((err) => {
					if (err.error.message == '查无此人') {
						uni.removeStorageSync('userInfo');
						this.userInfo = {};
						this.resetLogin();
					}
				})
				.finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh(); // 停止下拉刷新
				});
		},
		editUserInfo(msg) {
			const that = this;
			upImg(msg.detail.avatarUrl)
				.then(async (avatarUrl) => {
					that.editInfo({ avatarUrl });
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		valueChange(e) {
			if (!['微信用户', '微信昵称'].includes(e.detail.value)) {
				this.editInfo({ nickName: e.detail.value });
			}
		},
		editInfo(info) {
			editUserInfo({ ...this.userInfo, ...info }).then((res) => {
				this.$Message('修改成功');
				this.userInfo = { ...this.userInfo, ...info };
				uni.setStorageSync('userInfo', this.userInfo);
			});
		},
		async addRecord() {
			addRecord({ ...this.userInfo }).then((res) => {
				this.userInfo = { recordId: res.id };
				this.$tn('/bill/addStart?recordId=' + res.id);
			});
		},
		async tnRoom() {
			const { recordId, openid, nickName, avatarUrl } = this.userInfo;
			if (['微信用户', '微信昵称'].includes(nickName)) {
				this.$Message('请先修改用户昵称');
				return;
			}
			uni.showLoading();
			try {
				if (recordId) {
					//1未结束游戏，0已结束游戏
					const record = await getRecord({ id: recordId });
					console.log(record, 'record');
					if (record.status == 1) {
						if (!record.userList.some((item) => item.openid == openid)) {
							record.userList.push({
								nickName,
								avatarUrl,
								newIntegral: 0,
								openid
							});
							await putRecord({
								...record
							});
						}
						this.$tn('/bill/addStart?recordId=' + recordId);
					} else {
						this.addRecord();
					}
					uni.hideLoading();
				} else {
					this.addRecord();
				}
			} catch (e) {
				this.$Message(e);
				uni.hideLoading();
			}
		}
	}
};
</script>

<style>
page {
	background: linear-gradient(180deg, #94ceff 0%, #fbfbfb 50%, #ffffff 100%);
}
</style>

<style scoped lang="scss">
::v-deep .u-cell__body--large {
	padding: 30rpx 0 !important;
}
input {
	text-align: right;
}
.box {
	padding: 30rpx;
	.head {
		margin-top: 80rpx;
	}
	.img {
		padding: 15rpx;
		border-radius: 50%;
		margin-bottom: 15rpx;

		border: 2rpx solid #ffffff;
		image {
			border-radius: 50%;
			width: 200rpx;
			height: 200rpx;
		}
	}
	.nickNameSty {
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 15rpx;
	}
	.integral {
		font-size: 40rpx;
		color: red;
	}
	.session {
		font-size: 40rpx;
	}
	.label {
		color: #cccccc;
		font-weight: 400;
	}
}
.begin {
	margin-top: 40rpx;
	color: #ffffff;
	padding: 30rpx;
	background-color: #9ed2fe;
	text-align: center;
	width: 100%;
	border-radius: 15rpx;
	font-size: 30rpx;
	font-weight: bold;
}
.btnImg {
	width: 100%;
	background-color: #ffffff;
	text-align: right;
}
.recordBox {
	padding: 30rpx;
	height: 850rpx;
	overflow-y: auto;
}
</style>
